<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <a-card>
      <titleName title="基本信息"></titleName>
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="16"
            :sm="16"
          >
            <a-form-model-item
              label="所属单位"
              prop="projectId"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
              <org-tree-select
                v-model="form.projectId"
                disabled
                isAutoSelectFirst
                checkStrictly
                @select="selectOrg"
                @getProjectInfo="selectChange"
              ></org-tree-select>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属分公司" prop="branchComId">
                            <SelectSubCompany
                                :isDefaultSelected="pageType == 'add'"
                                placeholder="请选择"
                                v-model="form.branchComId"
                                disabled
                            ></SelectSubCompany>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属项目" prop="projectId">
                            <SelectProject
                                :isDefaultSelected="pageType == 'add'"
                                placeholder="请选择"
                                v-model="form.projectId"
                                :form="form"
                                :isClear="id == ''"
                                keyValue="branchComId"
                                @selectChange="selectChange"
                                disabled
                            ></SelectProject>
                        </a-form-model-item>
                    </a-col> -->
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="退回申请人"
              prop="returnApplierId"
            >
              <SelectPersonByProject
                :is-org="true"
                v-model="form.returnApplierId"
                :org-id="form.projectDeptId"
                :currentLabel.sync="form.returnApplier"
                :show-search="true"
                mode="combobox"
                placeholder="请选择"
                :disabled="pageType == 'look'"
                option-label-prop="children"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="身份证号码"
              prop="returnApplierIDCard"
            >
              <BaseInput
                :disabled="pageType == 'look'"
                placeholder="请输入"
                v-model="form.returnApplierIDCard"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="申请人岗位"
              prop="postInfo"
            >
              <SelectProjectJob
                v-model="form.postInfo"
                :projectDeptId="form.projectDeptId"
                :isClear="id == ''"
                :disabled="pageType == 'look'"
              />
              <!-- <BaseInput :disabled="pageType == 'look'" placeholder="请输入" v-model="form.bankAccount" /> -->
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="银行账号"
              prop="bankAccount"
            >
              <BaseInput
                :disabled="pageType == 'look'"
                placeholder="请输入"
                v-model="form.bankAccount"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="开户行名称"
              prop="accountBankName"
            >
              <BaseInput
                :disabled="pageType == 'look'"
                placeholder="请输入"
                v-model="form.accountBankName"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            v-if="pageType != 'look'"
            :md="24"
            :sm="24"
          >
            <a-form-model-item label="申请人承诺书扫描件">
              <upload-list
                :businessCode="'BM25'"
                :uploadArrys.sync="form.fileInfoVOList"
                @fileArrysData="handleFileUploaded"
                multiple
              ></upload-list>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
            v-else
          >
            <a-form-model-item label="申请人承诺书扫描件">
              <file-link :fileList="form.fileInfoVOList"></file-link>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <a-card v-if="pageType == 'look' && form.compAuditVO">
      <titleName title="公司综合部意见"></titleName>
      <a-form-model
        ref="ruleForm3"
        :model="form.compAuditVO"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              该同志原有项目风险金按《项目部人员风险金预留分配表》中核定的金额
              <a-form-model-item
                :colon="false"
                label=" "
                prop="reserveTransferAmount"
                :style="{ display: 'inline-block' }"
              >
                <a-input-number
                  :min="0"
                  disabled
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.compAuditVO.reserveTransferAmount"
                />
              </a-form-model-item>
              元已全部预留。
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              该同志进入项目时间
              <a-form-model-item
                :colon="false"
                label=" "
                prop="entryDate"
                :style="{ display: 'inline-block' }"
              >
                <a-date-picker
                  disabled
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.compAuditVO.entryDate"
                />
              </a-form-model-item>
              离开时间
              <a-form-model-item
                :colon="false"
                label=" "
                prop="exitDate"
                :style="{ display: 'inline-block' }"
              >
                <a-date-picker
                  disabled
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.compAuditVO.exitDate"
                />
              </a-form-model-item>
              ，共计天数
              <a-form-model-item
                :colon="false"
                label=" "
                prop="totalDays"
                :style="{ display: 'inline-block' }"
              >
                <a-input
                  disabled
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.compAuditVO.totalDays"
                />
              </a-form-model-item>。
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              本次从
              <a-form-model-item
                :colon="false"
                label=" "
                :style="{ display: 'inline-block' }"
              >
                <org-tree-select
                  v-model="form.projectId"
                  disabled
                  isAutoSelectFirst
                  checkStrictly
                  style="width: 250px; margin-top: -34px"
                ></org-tree-select>
              </a-form-model-item>
              项目，将预留风险金的
              <a-form-model-item
                :colon="false"
                label=" "
                :style="{ display: 'inline-block' }"
                prop="reserveRatio"
              >
                <a-input-number
                  :min="0"
                  disabled
                  style="width: 200px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.compAuditVO.reserveRatio"
                />
              </a-form-model-item>
              %，计
              <a-form-model-item
                :colon="false"
                label=" "
                :style="{ display: 'inline-block' }"
                prop="reserveAmount"
              >
                <a-input-number
                  disabled
                  :min="0"
                  style="width: 200px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.compAuditVO.reserveAmount"
                />
              </a-form-model-item>
              元。 转抵至
              <a-form-model-item
                :colon="false"
                label=" "
                :style="{ display: 'inline-block' }"
                prop="branchComId"
              >
                <SelectSubCompany
                  disabled
                  style="width: 200px; margin-top: -34px"
                  placeholder="请选择"
                  v-model="form.compAuditVO.branchComId"
                ></SelectSubCompany>
              </a-form-model-item>&nbsp;
              <a-form-model-item
                :colon="false"
                label=" "
                :style="{ display: 'inline-block' }"
                prop="projectId"
              >
                <SelectProject
                  disabled
                  style="width: 200px; margin-top: -34px"
                  placeholder="请选择"
                  v-model="form.compAuditVO.projectId"
                  :form="form"
                  :isClear="id == ''"
                  keyValue="branchComId"
                ></SelectProject>
              </a-form-model-item>
              项目
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card v-if="pageType == 'look' && form.financeAuditVO">
      <titleName title="公司财务资金部意见"></titleName>
      <a-form-model
        ref="ruleForm1"
        :model="form.financeAuditVO"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              该同志原有项目风险金按《项目部人员风险金预留分配表》中核定的金额
              <a-form-model-item
                :colon="false"
                label=" "
                prop="creditAmount"
                :style="{ display: 'inline-block' }"
              >
                <a-input-number
                  :min="0"
                  disabled
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.financeAuditVO.creditAmount"
                />
              </a-form-model-item>
              元已全部预留。
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="审批意见"
              prop="financeOpinions"
            >
              <BaseTextarea
                disabled
                placeholder="请输入"
                v-model="form.financeAuditVO.financeOpinions"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <!-- v-if="taskDefKey == 'GS_SWGLBJL_AUDIT'" -->
    <a-card v-if="pageType == 'look' && form.commercialAuditVO">
      <titleName title="公司商务管理部意见"></titleName>
      <a-form-model
        ref="ruleForm2"
        :model="form.commercialAuditVO"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label=""
              class="item"
            >
              根据《商务管理手册》规定，建议将该同志原来在项目预留风险金
              <a-form-model-item
                :colon="false"
                label=" "
                prop="transferAmount"
                :style="{ display: 'inline-block' }"
              >
                <a-input-number
                  disabled
                  :min="0"
                  style="width: 350px; margin-top: -34px"
                  placeholder="请输入"
                  v-model="form.commercialAuditVO.transferAmount"
                />
              </a-form-model-item>
              元予以转抵。
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="审批意见"
              prop="commercialOpinions"
            >
              <BaseTextarea
                disabled
                placeholder="请输入"
                v-model="form.commercialAuditVO.commercialOpinions"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <div
      class="tool-btns page-btn-right-top"
      v-if="pageType != 'look'"
    >
      <a-button
        v-if="id != '' && form.auditStatus == 'DRAFT'"
        type="danger"
        :loading="loading.DELETE"
        @click="handleSave('DELETE')"
      >删除草稿</a-button>
      <a-button
        v-if="form.auditStatus == 'REJECTED'"
        type="primary"
        :loading="loading.REJECTED"
        @click="handleSave('REJECTED')"
      >保存</a-button>
      <a-button
        v-else
        type="primary"
        :loading="loading.DRAFT"
        @click="handleSave('DRAFT')"
      >保存草稿</a-button>
      <a-button
        type="primary"
        :loading="loading.SUBMITTED"
        @click="handleSave('SUBMITTED')"
      >提交</a-button>
      <a-button
        type="primary"
        @click="handleClose"
      >关闭</a-button>
    </div>
    <div
      class="tool-btns page-btn-right-top"
      v-else
    >
      <BasePrintButton
        type="primary"
        v-if="form.auditStatus == 'PAST'"
        :beforePrintFn="checkPersonalRiskTransferPrint"
      />
      <a-button
        type="primary"
        class="ml20"
        @click="handleClose"
        v-if="checkVisibleInDetail"
      >关闭</a-button>
    </div>
    <selectApprover
      :businessId="businessId"
      :processConfig="setProcessConfig"
    ></selectApprover>
  </base-breadcrumb>
</template>
<script>
import { getPersonalRiskTransfer, addPersonalRiskTransfer, editPersonalRiskTransfer, delPersonalRiskTransfer, checkPersonalRiskTransfer, checkPersonalRiskTransferPrint } from '@/api/businessAffairs/riskRefund'

import { createValidator, idCard } from '@/utils/regExpression' // 正则校验

import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectProjectJob from '@/components/Select/SelectProjectJob' // 项目
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import UploadList from '@/components/UploadList'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    SelectProjectJob,
    UploadList,
    BasePrintButton,
    SelectPersonByProject
  },

  data() {
    const bankAccount = (rule, value, callback) => {
      const reg = /^(\d{16}|\d{19})$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的银行卡号'))
      } else {
        callback()
      }
    }
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      fetchingOrganizePeopleList: false,
      organizePeopleList: [],
      form: {
        financeAuditVO: null,
        commercialAuditVO: null,
        compAuditVO: null,
        projectDeptId: void 0,
        returnApplierId: void 0,
        projectId:null
      },
      rules: {
        branchComId: [{ required: true, message: '请选择分公司' }],
        projectId: [{ required: true, message: '请选择项目' }],
        bankAccount: [{ required: true, validator: bankAccount, trigger: 'blur' }],
        accountBankName: [{ required: true, message: '请输入' }],
        returnApplierIDCard: [{ required: true, validator: createValidator(idCard, '请输入正确的身份证', true), trigger: 'blur' }],
        postInfo: [{ required: true, message: '请选择岗位' }],
        returnApplierId: [{ required: true, message: '请选择' }]
      },
      id: '',
      pageType: '',
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.pageType = 'look'
          })
        }
      }
    }
  },
  async mounted() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      console.log(this.id)
      this.checkPersonalRiskTransferReq()
    }else{
      this.form.projectId = this.$userInfo().currentPost.projectId;
    }
    this.pageType = this.$route.query.pageType
    console.log(this.pageType)
    if (this.pageType == 'look') {
      this.$route.meta.title = '个人风险金转抵查看'
    } else {
      this.$route.meta.title = this.id == '' ? '个人风险金转抵新增' : '个人风险金转抵编辑'
      // if (this.pageType == 'add') {
      //     this.$nextTick(() => {
      //         this.form.returnApplierId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).id
      //     })
      // }
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_pre_reserve_risk_fund_transfer_apply')
  },
  methods: {
    //选择单位
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId
      }
    },
    checkPersonalRiskTransferPrint() {
      return checkPersonalRiskTransferPrint({ id: this.id }).then((res) => {
        console.log(res)
        return res[1].data.content
      })
    },
    async checkPersonalRiskTransferReq() {
      const [err, res] = await checkPersonalRiskTransfer({ id: this.id })
      if (!err) {
        this.form = { ...this.form, ...res.data }
        // this.getOrganizePeopleList()
      }
    },
    selectChange(e) {
      this.$nextTick(() => {
        // this.$set(this.form,'projectDeptId',e.projectDeptId)
        this.form.projectDeptId = e.projectDeptOrgId
        console.log(this.form)
      })
    },
    //查询人员基本信息
    changeEmployeeId(e) {
      this.getOrgEmployeeByUser(e)
    },
    async getOrgEmployeeByUser(id) {
      try {
        const employee = await getInfoByStaffId(id)

        if (employee.data.idCard) {
          this.form.returnApplierIDCard = employee.data.idCard
        }

        console.log(this.formInfo)
      } catch (err) {
        console.error(err)
      }
    },
    //获取项目下的人员列表
    // getOrganizePeopleList() {
    //     // console.log(this.form)
    //     this.$nextTick(() => {
    //         // this.form.returnApplierId = '' // 清空退回申请人
    //         let params = {
    //             id: this.form.projectId
    //         }
    //         this.organizePeopleList = []
    //         this.fetchingOrganizePeopleList = true
    //         getOrganizePeopleList(params).then((res) => {
    //             this.fetchingOrganizePeopleList = false
    //             let obj = {}
    //             res.data = res.data.reduce((cur, next) => {
    //                 obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
    //                 return cur
    //             }, []) //设置cur默认类型为数组，并且初始值为空的数组
    //             console.log(res.data)
    //             this.organizePeopleList = res.data || []
    //         })

    //         console.log(this.organizePeopleList)
    //     })
    // },
    handleFileUploaded(list) {
      this.form.fileInfoVOList = [...list]
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((valid) => {
        if(!valid) {
          this.$message.warning("请填写完所有必填项信息")
        }
        flag = valid
      })
      return flag
    },
    async delPersonalRiskTransfer(params) {
      const [err, res] = await delPersonalRiskTransfer(params)
      if (!err) {
        this.$message.success('成功')
        this.handleClose()
      }
    },
    // 处理增、删、改操作
    async handleSave(status) {
      this.setProcessConfig = null
      if (status != 'DELETE') {
        if (!this.validateForm()) return
        if (isAttachment(this, status, this.form.fileInfoVOList)) return
      }
      if (this.loading[status]) return

      const params = {
        ...this.form,
        auditStatus: status
        // id: this.$route.query.id || void 0,
      }
      const { pageType } = this.$route.query
      const fn = pageType === 'edit' ? editPersonalRiskTransfer : addPersonalRiskTransfer
      const delParams = {id:params.id,type:1}
      const map = {
        DELETE: delPersonalRiskTransfer,
        DRAFT: fn,
        SUBMITTED: fn,
        REJECTED: fn
      }
      if (status == 'DELETE') {
        let that = this
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return that.delPersonalRiskTransfer(delParams)
          }
        })
      } else {
        this.submitApprovalConfirm(status == 'SUBMITTED'?this.processConfig:6, async (flag)=>{
          if(!flag) {
            this.loading[status] = false
            return
          }
        this.loading[status] = true
        const [err, res] = await map[status](params)
        if (!err) {
          this.$message.success('成功')
          if (status == 'SUBMITTED') {
            //提交时，返回id
            this.businessId = res.data.id
            this.setProcessConfig = this.processConfig
            return
          } else {
            this.handleClose()
          }
        }

        this.loading[status] = false
        })
      }
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
.tx {
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  margin-left: 30px;
}
.return-ratio .ant-form-item-children .ant-form-explain {
  margin-left: 230px;
}
.inputStyl {
  border-color: #e4ac0b;
  background-color: #fff9e8;
}
.item {
  margin-left: 60px;
}
.item .ant-form-item {
  margin-top: -28px;
}
.ant-form {
  min-height: 400px;
}
</style>
